#!/usr/bin/env python3
import subprocess
import logging
import time
from pathlib import Path
from datetime import datetime
import platform
from utils import upload_pgyer as PgyerUtil

# 设置日志级别
logging.basicConfig(level=logging.INFO)


# 上传完成回调
def upload_complete_callback(isSuccess, result):
    if isSuccess:
        print('上传完成')
        _data = result['data']
        _url = _data['buildShortcutUrl'].strip()  # 去除首尾空格
        _appVer = _data['buildVersion']
        _buildVer = _data['buildBuildVersion']
        print('链接: https://www.pgyer.com/%s' % _url)
        print('版本: %s (build %s)' % (_appVer, _buildVer))
    else:
        print('上传失败')


def rename_apk(old_path, new_path):
    if old_path.is_file():
        if new_path.exists():
            logging.warning(f"文件 {new_path} 已存在，将被覆盖")
        old_path.rename(new_path)
        logging.info(f"已将APK文件重命名为 {new_path}")
    else:
        logging.error(f"未找到APK文件 {old_path}")


def up(new_path):
    update_description = 'app更新了'
    # 输入更新内容，如果输入则使用输入的值，如果输入的值为空则使用默认值
    update_description = input('请输入更新内容,点击enter确定(默认: %s): ' % update_description)

    PgyerUtil.upload_to_pgyer(
        path=new_path,
        api_key='51703a1d7b85abc64a6727ab4a9d7812',
        install_type=1,
        # (选填)应用安装方式，值为(1,2,3，默认为1 公开安装)。1：公开安装，2：密码安装，3：邀请安装
        update_description=update_description,
        callback=upload_complete_callback
    )


def build_apk(channel, app_name):
    if not isinstance(channel, str) or not isinstance(app_name, str):
        logging.error("channel 和 app_name 必须是字符串")
        return

    cmd = f"flutter build apk --release --dart-define=APP_INSTALL_CHANNEL={channel} --dart-define=APP_NAME={app_name} --split-per-abi"

    try:
        # 开始打包
        logging.info(f"开始打包 {channel} {app_name}...")
        subprocess.check_call(cmd, shell=True)
        logging.info("打包完成.")

        # 获取当前日期和时间
        now = datetime.now()
        # 创建一个包含日期和时间的字符串
        date_time = now.strftime("%Y-%m-%d-%H-%M-%S")

        # 修改包文件名字
        # 使用Path.joinpath()连接路径
        old_path = Path().joinpath(".", "build", "app", "outputs", "flutter-apk", "app-arm64-v8a-release.apk")
        new_path = Path().joinpath(".", "build", "app", "outputs", "flutter-apk", f"{app_name}_{date_time}.apk")
        if old_path.is_file():
            old_path.rename(new_path)
            logging.info(f"已将APK文件重命名为 {new_path}")

            time.sleep(1)
            is_upload = 'y'
            is_upload = input('是否上传到蒲公英? y/n(默认: %s): ' % is_upload)
            if is_upload == 'y':
                up(new_path)
            elif is_upload == 'n':
                # 打开打包后的文件夹
                # 判断如果是Windows系统，使用start命令打开文件夹 如果是macOS系统，使用open命令打开文件夹
                if platform.system() == "Windows":
                    subprocess.check_call(r"start .\build\app\outputs\flutter-apk", shell=True)
                elif platform.system() == "Linux":
                    subprocess.check_call(r"xdg-open ./build/app/outputs/flutter-apk", shell=True)
                else:
                    subprocess.check_call(r"open ./build/app/outputs/flutter-apk", shell=True)

        else:
            logging.error(f"未找到APK文件 {old_path},返回上一目录查找")
            old_path = Path().joinpath("..", "build", "app", "outputs", "flutter-apk", "app-arm64-v8a-release.apk")
            new_path = Path().joinpath("..", "build", "app", "outputs", "flutter-apk", f"{app_name}_{date_time}.apk")
            old_path.rename(new_path)
            logging.info(f"已将APK文件重命名为 {new_path}")

            time.sleep(1)
            is_upload = 'y'
            is_upload = input('是否上传到蒲公英? y/n(默认: %s): ' % is_upload)
            if is_upload == 'y':
                up(new_path)
            elif is_upload == 'n':
                # 打开打包后的文件夹
                # 判断如果是Windows系统，使用start命令打开文件夹 如果是macOS系统，使用open命令打开文件夹
                if platform.system() == "Windows":
                    subprocess.check_call(r"start ..\build\app\outputs\flutter-apk", shell=True)
                elif platform.system() == "Linux":
                    subprocess.check_call(r"xdg-open ../build/app/outputs/flutter-apk", shell=True)
                else:
                    subprocess.check_call(r"open ./build/app/outputs/flutter-apk", shell=True)


    except Exception as e:
        logging.error(f"打包失败: {e}")
